<template>
  <el-tabs v-model="activeTab" @tab-click="handleTabClick">
    <!-- 借用记录 -->
    <el-tab-pane label="借用记录" name="borrow">
      <el-button type="primary" @click="dialogVisible = true" style="margin-bottom: 16px;">新增借用</el-button>

      <el-table :data="borrowList" border style="width: 100%;">
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template #default="props">
            <div style="padding: 10px;">
              <!-- 仪器图片 -->
              <div style="display: flex; flex-direction: column;  margin-bottom: 16px;">
                <strong style="margin-bottom: 8px;">仪器图片：</strong>
                <div style="display: flex;  flex-wrap: wrap;">
                  <el-image
                      @click="previewImg = `/api/src/img/${img}`"
                      v-for="(img, index) in props.row.instrumentImgs"
                      :key="'instrument-' + index"
                      :src="`/api/src/img/${img}`"
                      style="width: 100px; height: 100px; margin: 5px"
                      fit="cover"

                  />
                </div>
              </div>
              <!-- 归还图片 -->
              <div style="display: flex; flex-direction: column;  margin-bottom: 16px;">
                <strong style="margin-bottom: 8px;">归还图片：</strong>
                <div style="display: flex; flex-wrap: wrap;">
                  <el-image
                      @click="previewImg = `/api/src/img/${img}`"
                      v-for="(img, index) in props.row['returnInstrumentImgs']"
                      :key="'return-' + index"
                      :src="`/api/src/img/${img}`"
                      style="width: 100px; height: 100px; margin: 5px"
                      fit="cover"
                  />
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="编号" prop="id" width="80"/>
        <el-table-column label="类型" prop="type" width="100">
          <template #default="scope">
            {{ scope === "UP" ? "用户上传" : "仪器列表" }}
          </template>
        </el-table-column>
        <el-table-column label="借用人姓名" prop="realName" width="150"/>
        <el-table-column label="仪器名称" prop="instrumentName" width="150"/>
        <el-table-column label="借用时间" prop="borrowTime" width="180"/>
        <el-table-column label="归还时间" prop="returnTime" width="180"/>
        <el-table-column label="备注" prop="remark" width="180"/>
        <el-table-column label="状态" prop="statusName"/>
      </el-table>

      <el-pagination
          v-model:current-page="borrowPage"
          :page-size="pageSize"
          :total="borrowTotal"
          @current-change="loadBorrowList"
          layout="total, prev, pager, next"
          background
          style="margin-top: 16px"
      />
    </el-tab-pane>

    <!-- 待审核 -->
    <el-tab-pane label="待审核" name="review">
      <el-table :data="reviewList" border style="width: 100%;" row-key="id" >
        <el-table-column type="expand">
          <template #default="props">

              <!-- 仪器图片 -->
              <div style="display: flex; flex-direction: column; margin-bottom: 16px; padding: 10px">
                <strong style="margin-bottom: 8px;">仪器图片：</strong>
                <div style="display: flex;  flex-wrap: wrap;">
                  <el-image
                      @click="previewImg = `/api/src/img/${img}`"
                      v-for="(img, index) in props.row.instrumentImgs"
                      :key="'instrument-' + index"
                      :src="`/api/src/img/${img}`"
                      style="width: 100px; height: 100px; margin: 5px"
                      fit="cover"
                  />
                </div>
              </div>
          </template>
        </el-table-column>
        <el-table-column label="编号" prop="id" width="80"/>
        <el-table-column label="类型" prop="type" width="100">
          <template #default="scope">
            {{ scope === "UP" ? "用户上传" : "仪器列表" }}
          </template>
        </el-table-column>
        <el-table-column label="借用人姓名" prop="realName" width="150"/>
        <el-table-column label="仪器名称" prop="instrumentName" width="150"/>
        <el-table-column label="借用时间" prop="borrowTime" width="180"/>
        <el-table-column label="备注" prop="remark" width="180"/>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="success" @click="approve(scope.row)">通过</el-button>
            <el-button size="small" type="danger" @click="reject(scope.row)">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-model:current-page="reviewPage"
          :page-size="pageSize"
          :total="reviewTotal"
          @current-change="loadReviewList"
          layout="prev, pager, next"
          background
          style="margin-top: 16px"
      />
    </el-tab-pane>
  </el-tabs>

  <!-- 新增借用对话框 -->
  <el-dialog v-model="dialogVisible" title="新增借用记录" width="500px">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="仪器ID" prop="instrumentId">
        <el-input v-model="form.instrumentId" />
      </el-form-item>
      <el-form-item label="仪器名称" prop="instrumentName">
        <el-input v-model="form.instrumentName" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-input v-model="form.type" />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="form.userId" />
      </el-form-item>
      <el-form-item label="借用时间" prop="borrowTime">
        <el-date-picker v-model="form.borrowTime" type="datetime" />
      </el-form-item>
      <el-form-item label="审核人ID" prop="reviewerId">
        <el-input v-model="form.reviewerId" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="form.remark" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="previewImg" append-to-body style="width: 35vw;">
    <img :src="previewImg" style=" width: 100%"  alt=""/>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/apps/admin/utils/request.js'

const activeTab = ref('borrow')

const previewImg = ref()
const dialogVisible = ref(false)
const formRef = ref(null)
const form = reactive({
  instrumentId: '',
  instrumentName: '',
  type: '',
  userId: '',
  borrowTime: '',
  reviewerId: '',
  remark: ''
})

const rules = {
  instrumentId: [{ required: true, message: '请输入仪器ID', trigger: 'blur' }],
  instrumentName: [{ required: true, message: '请输入仪器名称', trigger: 'blur' }],
  type: [{ required: true, message: '请输入类型', trigger: 'blur' }],
  userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  borrowTime: [{ required: true, message: '请选择借用时间', trigger: 'change' }],
  reviewerId: [{ required: true, message: '请输入审核人ID', trigger: 'blur' }]
}

// 借用记录分页数据
const borrowList = ref([])
const borrowPage = ref(1)
const borrowTotal = ref(0)

// 审核记录分页数据
const reviewList = ref([])
const reviewPage = ref(1)
const reviewTotal = ref(0)

const pageSize = 10

// 加载借用记录
const loadBorrowList = async () => {
  const res = await request.get('/v1/admin/getInstrumentLoans', {
    params: { page: borrowPage.value, size: pageSize }
  })
  borrowList.value = res.data["records"]
  borrowTotal.value = res.data.total
}

// 加载待审核记录
const loadReviewList = async () => {
  const res = await request.get('/v1/admin/getInstrumentLoansByNotReview', {
    params: { page: reviewPage.value, size: pageSize }
  })
  reviewList.value = res.data["records"]
  reviewTotal.value = res.data.total
}

// 审核通过
const approve = async (row) => {
  if (row.type === "UP"){
    ElMessageBox.prompt('输入用户借用仪器要扣除的积分', '扣除积分', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /^\d+$/,
      inputErrorMessage: '请输入整数',
    }).then(async ({value}) => {
      const res = await request.post('/v1/admin/approveInstrumentLoanByUp', {
        id: row.id,
        points: value - 0
      })
      if (res["code"] === 200) {
        ElMessage.success('审核通过')
        await loadReviewList()
      } else {
        ElMessage.error(res["msg"] || '审核失败')
      }
    })
    return;
  }
  try {
    await ElMessageBox.confirm(`确认通过借用记录 ID: ${row.id}？`, '提示', { type: 'warning' })
    const res = await request.post('/v1/admin/approveInstrumentLoan', { id: row.id })
    if (res["code"] === 200) {
      ElMessage.success('审核通过')
      await loadReviewList()
    } else {
      ElMessage.error(res["msg"] || '审核失败')
    }
  } catch {}
}

// 审核拒绝
const reject = async (row) => {
  try {
    await ElMessageBox.confirm(`确认拒绝借用记录 ID: ${row.id}？`, '提示', { type: 'warning' })
    const res = await request.post('/v1/admin/rejectInstrumentLoan', { id: row.id })
    if (res["code"] === 200) {
      ElMessage.success('已拒绝')
      await loadReviewList()
    } else {
      ElMessage.error(res["msg"] || '拒绝失败')
    }
  } catch {}
}

// 提交新增表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await request.post('/v1/admin/createInstrumentLoan', form)
        if (res.code === 200) {
          ElMessage.success('新增借用记录成功')
          dialogVisible.value = false
          await loadBorrowList()
        } else {
          ElMessage.error(res.msg || '提交失败')
        }
      } catch {
        ElMessage.error('提交失败')
      }
    }
  })
}

// 标签切换
const handleTabClick = (tab) => {
  if (tab.paneName === 'borrow') {
    loadBorrowList()
  } else {
    loadReviewList()
  }
}

onMounted(() => {
  loadBorrowList()
})
</script>

<style scoped>
/* 提高图片预览的层级，防止被表格遮住 */
:deep(.el-image-viewer__wrapper) {
  z-index: 3000 !important;
}

/* 允许表格内元素超出显示（防止 overflow 造成遮挡） */
:deep(.el-table) {
  overflow: visible !important;
}
</style>
